import asyncio
from typing import List

from django.core.files.uploadedfile import InMemoryUploadedFile
from rest_framework.views import APIView
from HomeAutoAI.common.Results import HttpResult
from llm.entity.vo.FIleUploadVO import FileUploadVO

from llm.service.FileService import FileService


class FileUploadView(APIView):
    def post(self, request):
        """
        统一文件上传接口，可以直接返回上传带OpenAI的file id，，和其他接口组合使用实现不同的上传场景
        :param request:
        :return:
        """
        try:
            # print(f"1+{request.FILES}")
            file_objects: List[InMemoryUploadedFile] = request.FILES.getlist('files')
            print(f"2:+{file_objects}")
            # print(type(file_object))
            if len(file_objects) == 0:
                return HttpResult.error(message="没有文件上传")
            # 将文件写入项目的指定文件夹
            file_models = FileService.create(file_objects)
            fileVO = FileUploadVO()
            for file_object in file_models:
                fileVO.file_ids.append(file_object.id)
                fileVO.file_num += 1
            return HttpResult.success(data=fileVO.dict(),
                                      message="文件上传成功")
        except Exception as e:
            return HttpResult.error(message=str(e))
